package com.sbl.bajw.pc.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.pc.model.AppVersionTModel;
import com.sbl.bajw.pc.service.AppVersionTModelService;
import com.sbl.bajw.util.JsonUtil;
import com.sbl.bajw.util.LogUtil;

@Controller
@RequestMapping("/AppVersionTModel")
public class AppVersionTModelAction {
	
	@Resource
	private AppVersionTModelService service;
	
	static Logger log;
	
	static{
		log = LogUtil.getLogger("AppVersionTModel");
	}
	
	@RequestMapping(value = "/insert")
	public @ResponseBody String insert(HttpServletRequest request, HttpServletResponse response) throws Exception{
		AppVersionTModel model = RequestUnit.getModel(AppVersionTModel.class);
		String json = "";
		try {
			log.info("appVersionModel："+model.getAppName()+","+model.getAppType()+","+model.getAppVersiton()+","+model.getAppCode());
			service.insert(model);
			json += "{\"code\":\"1\",";
			json += "\"msg\":\"上传成功\",";
			json += "\"success\":\"true\"}";
		} catch (Exception e) {
			log.error("上传App失败", e);
			throw new MessageException("系统异常", "4");
		}
		return json;
	}
	
	@RequestMapping(value = "/ApkDownLoad")
	public void ApkDownLoad(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String url = WebContext.getWebInitParameter("ApkDownLoadUrl");
		response.sendRedirect(url);
	}
	
	@RequestMapping("/checkVersion")
	public @ResponseBody String checkVersion(HttpServletRequest request, HttpServletResponse response){
		String userId = RequestUnit.getString("user_id");
		String version = RequestUnit.getString("version");
		String appName = RequestUnit.getString("app_name");
		Map<String, Object> map = new HashMap<String, Object>();
		HashMap<String, Object> parm  = new HashMap<String, Object>();
		map.put("code", "1");
		map.put("msg", "检查完成");
		map.put("success", "true");
		log.info("==>" + userId + "，==》version：" + version + ",appName：" + appName);
		if(appName != null && !appName.equals("")){
			parm = service.getVersion(appName);
		}else{
			parm = service.getVersion("bajw");
		}
		if(parm != null && !"".equals(parm)){
			if(version.compareTo(String.valueOf(parm.get("APP_VERSITON"))) >= 0){
				map.put("data", "");
			}else{
				map.put("data", parm.get("APP_URL"));
			}
		}else{
			map.put("data", "");
		}
		log.info("==>VERSITON：" + parm.get("APP_VERSITON") + ",url：" + map.get("data"));
		return JsonUtil.ConvertObjectToJson(map);
	}
}
